#备份目录所有ini文件
import os
import shutil
import time
import zipfile
import socket

def backup_ini_files(directory_path, backup_directory_path):
    # 获取当前日期和时间
    timestamp = time.strftime("%Y%m%d-%H")
    hosk = socket.gethostname()
    backup_dir = os.path.join(backup_directory_path, f"{hosk}_{timestamp}_Data")

    # 创建备份目录
    os.makedirs(backup_dir, exist_ok=True)

    # 遍历目录中的所有文件
    for filename in os.listdir(directory_path):
        if filename.endswith('.ini'):
            src_file = os.path.join(directory_path, filename)
            dst_file = os.path.join(backup_dir, filename)
            shutil.copy2(src_file, dst_file)  # 复制文件并保留元数据

    print(f"备份完成，备份目录: {backup_dir}")

    # 打包成 .zip 文件
    zip_filename = os.path.join(backup_directory_path, f"{hosk}_{timestamp}_Data.zip")
    with zipfile.ZipFile(zip_filename, 'w', zipfile.ZIP_DEFLATED) as zf:
        for root, dirs, files in os.walk(backup_dir):
            for file in files:
                zf.write(os.path.join(root, file), arcname=os.path.relpath(os.path.join(root, file), backup_dir))

    print(f"备份文件已打包成: {zip_filename}")

    # 删除原始备份目录
    shutil.rmtree(backup_dir)
    print(f"原始备份目录已删除: {backup_dir}")
    with open('log.txt', 'a', encoding='utf-8') as f:
        f.write(f"自动保存成功 -> {time.strftime('%Y-%m-%d %H:%M:%S', time.localtime())}，文件 -> {zip_filename}\n")

# # 示例调用
# directory_path = r"D:\Pycham\Python\ping\datatemp"
# backup_directory_path = r"D:\Pycham\Python\ping"
# backup_ini_files(directory_path, backup_directory_path)